<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Search, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { getUserListApi, delUserApi, updateUserApi } from '@/api/user'
import type { User } from '@/api/user/user'
import { ElMessageBox, ElMessage } from 'element-plus'
import { checkMobile } from '@/utils/validate'

const userFormRef = ref()
const userForm = ref({
  username: '',
  mobile: '',
  role_name: '',
  created_at: '',
  updated_at: '',
  pagenum: 1,
  pagesize: 10,
})
// 筛选框状态
const expand = ref(false)

// tableData
const userList = ref([] as User[])
let userListTotal = 0
const getUserList = async () => {
  const res = await getUserListApi(userForm.value)
  //   console.log(res.data.list)
  userList.value = res.data.list
  userListTotal = res.data.total
}
getUserList()

// 分页处理函数
const handleSizeChange = (newSize: number) => {
  userForm.value.pagesize = newSize
  getUserList()
}
const handleCurrentChange = (newPage: number) => {
  userForm.value.pagenum = newPage
  getUserList()
}

// 表单重置
const reset = () => {
  userFormRef.value.resetFields()
  userForm.value = {
    username: '',
    mobile: '',
    role_name: '',
    created_at: '',
    updated_at: '',
    pagenum: 1,
    pagesize: 10,
  }
  getUserList()
}

// 删除用户
const delUser = async (row: any) => {
  // 1.确认框实现确认
  const res = await ElMessageBox.confirm(
    '确定要删除该用户吗?',
    '温馨提示',
  ).catch(error => error)

  if (res === 'cancel') return
  // 2.实现删除
  await delUserApi(row)
  // 3.成功提示
  ElMessage.success('删除用户成功')
  // 4.重新加载数据
  getUserList()
}

// 编辑用户
// 点击编辑  弹出框中的表单有数据，数据哪里来的？
// 1. 直接获取表格中一行的用户数据 （当前项目）
// 2. 获取用户的id 根据id再去获取用户详情数据

const editUserVisible = ref(false)
const editUserInfo = ref()
const editUserFormRef = ref()
const userinfoRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ min: 6, max: 12, message: '请输入6~12位字符', trigger: 'blur' }],
  mobile: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (checkMobile(value)) {
          callback()
        } else {
          callback(new Error('手机号格式有误'))
        }
      },
      trigger: 'blur',
    },
  ],
}

const editUser = (row: any) => {
  editUserVisible.value = true
  editUserInfo.value = row
}

const updateUser = () => {
  // 兜底校验
  editUserFormRef.value.validate(async (valid: any) => {
    if (!valid) return

    // 1.收集数据更新用户信息
    await updateUserApi(editUserInfo.value)
    // 2.关闭弹出框
    editUserVisible.value = false
    // 3.更新成功提示
    ElMessage.success('更新用户成功')
    // 4.重新加载用户列表数据
    getUserList()
  })
}
</script>

<template>
  <!-- 筛选框 -->
  <el-card class="filter">
    <el-form :inline="true" :model="userForm" ref="userFormRef">
      <el-form-item label="用户名">
        <el-input
          v-model="userForm.username"
          placeholder="请输入用户名"
          clearable
        />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input
          v-model="userForm.mobile"
          placeholder="请输入手机号"
          clearable
        />
      </el-form-item>
      <el-form-item label="角色名" v-if="expand">
        <el-input
          v-model="userForm.role_name"
          placeholder="请输入角色名"
          clearable
        />
      </el-form-item>
      <el-form-item label="创建于" v-if="expand">
        <el-date-picker
          v-model="userForm.created_at"
          type="daterange"
          range-separator="到"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="更新于" v-if="expand">
        <el-date-picker
          v-model="userForm.updated_at"
          type="daterange"
          range-separator="到"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getUserList"
          >搜索</el-button
        >
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" text v-if="expand" @click="expand = false">
          收起
          <el-icon><ArrowUp /></el-icon>
        </el-button>
        <el-button type="primary" text v-else @click="expand = true">
          展开
          <el-icon><ArrowDown /></el-icon>
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 用户列表数据 -->
  <el-card>
    <template #header>
      <el-button type="danger">批量删除</el-button>
      <el-button type="primary">添加</el-button>
    </template>
    <el-table
      :data="userList"
      style="width: 100%"
      max-height="380"
      border
      stripe
    >
      <el-table-column prop="user_id" label="编号" width="200" align="center" />
      <el-table-column
        prop="role_name"
        label="所属角色"
        width="200"
        align="center"
      />
      <el-table-column prop="avatar" label="头像" width="200" align="center">
        <template v-slot="{ row }">
          <img
            :src="row.avatar"
            alt=""
            style="width: 40px; height: 40px; border-radius: 50%"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="username"
        label="用户名称"
        width="200"
        align="center"
      />
      <el-table-column
        prop="mobile"
        label="手机号"
        width="200"
        align="center"
      />
      <el-table-column prop="state" label="登录" width="200" align="center" />
      <el-table-column
        prop="created_at"
        label="创建于"
        width="200"
        align="center"
      />
      <el-table-column
        prop="updated_at"
        label="更新于"
        width="200"
        align="center"
      />
      <el-table-column
        fixed="right"
        label="操作"
        min-width="250"
        align="center"
      >
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="editUser(row)">
            编辑
          </el-button>
          <el-button type="success" size="small"> 分配角色 </el-button>
          <el-button type="danger" size="small" @click="delUser(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <!-- 分页
        current-page：当前处于页码值
        page-size：每页显示条数
        page-sizes： 数组  可改变的显示条数  数组中成员有一个要与page-size相
        layout: 布局
        total: 数据总条数
        @size-change：每页条数改变时触发
        @current-change：页码改变时触发
      -->
      <el-pagination
        v-model:current-page="userForm.pagenum"
        v-model:page-size="userForm.pagesize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="userListTotal"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </template>
  </el-card>

  <!-- 编辑用户弹出框 -->
  <el-dialog v-model="editUserVisible" title="编辑用户" width="500">
    <el-form
      ref="editUserFormRef"
      :model="editUserInfo"
      :rules="userinfoRules"
      label-width="auto"
      size="large"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          placeholder="请输入用户名"
          v-model="editUserInfo.username"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          placeholder="请输入密码"
          v-model="editUserInfo.password"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          placeholder="请输入手机号"
          v-model="editUserInfo.mobile"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editUserVisible = false">Cancel</el-button>
        <el-button type="primary" @click="updateUser"> 更新用户 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.filter {
  margin-bottom: 15px;
}
</style>
